$(function() {
    $(".login_nav").each(function() {
        $(this).parents().find("form").hide();
        $("li", this).each(function(index) {
            $(this).parents().find("form").eq(index).css("display", $(this).is(".on") ? "block" : "none");

            $(this).bind("click", function() {
                $(this).addClass("on").siblings().removeClass("on");
                $(this).parents().find("form").hide().eq(index).show();
            });
        });
    });
    validateKickout();
    initProvider();
    $('#PWDSignupForm').validate({
        submitHandler: function(form) {
            PWDLogin();
        }
    });
    $('#UKeySignupForm').validate({
        submitHandler: function(form) {
            UKeyLogin();
        }
    });
    $('.imgcode').click(function() {
        var url = ctx + "captcha/captchaImage?type=" + captchaType + "&s=" + Math.random();
        $(".imgcode").attr("src", url);
    });
});

function initProvider() {
    if (window.top.location.href != location.href) {
        window.top.location.href = location.href;
    }
    //页面加载完调枚举方法
    var CryptProv = window.document.getElementById("CryptProv");
    enumProvider(CryptProv);
}

function PWDLogin() {
    $.modal.loading($("#PWDBtnSubmit").data("loading"));
    var username = $.common.trim($("#PWDSignupForm input[name='username']").val());
    var password = $.common.trim($("#PWDSignupForm input[name='password']").val());
    var validateCode = $("#PWDSignupForm input[name='validateCode']").val();
    $.ajax({
        type: "post",
        url: ctx + "login",
        data: {
            "username": username,
            "password": password,
            "validateCode": validateCode,
        },
        success: function(r) {
            if (r.code == web_status.SUCCESS) {
                location.href = ctx + 'index';
            } else {
                $('.imgcode').click();
                $(".code").val("");
                $.modal.msg(r.msg);
            }
            $.modal.closeLoading();
        }
    });
}

function validatePWDRule() {
    var icon = "<i class='fa fa-times-circle'></i> ";
    $("#PWDSignupForm").validate({
        rules: {
            username: {
                required: true
            },
            password: {
                required: true
            }
        },
        messages: {
            username: {
                required: icon + "请输入您的用户名",
            },
            password: {
                required: icon + "请输入您的密码",
            }
        }
    })
}

//登录form表单提交
function UKeyLogin(){
    var userName = $.common.trim($("#UKeySignupForm input[name='username']").val());

    //初始化
    var ret = initProv(PROV_NAME, CONT_NAME);
    if(!ret){
        $.modal.alertError("初始化key失败" + ret);
        return false;
    }

    //获取证书
    var certData = getCert(CONT_NAME);
    if ($.common.isEmpty(certData) || 1 == certData) {
        $.modal.alertError('获取证书失败！');
        return false;
    }

    // 获取ukey获取随机数
    var clientRandNum = GenRandom(16);
    if ($.common.isEmpty(clientRandNum)) {
        return false;
    }

    // 获取服务端随机数
    var serverRandNum = getRandom();
    if ($.common.isEmpty(serverRandNum)) {
        return false;
    }
    var srcData = userName + "," + clientRandNum + "," + serverRandNum;
    console.log('srcData:' + srcData);
    var signData = signature(srcData, ALG_SIGN_RsaWithSHA256);
    // 如果点击取消那么签名值为空，直接返回
    console.log('signData:' + signData);
    if ($.common.isEmpty(signData)) {
        return false;
    }

    var data = {'userName': userName, 'signData': signData, 'random': clientRandNum};
    $.modal.loading($("#UKeyBtnSubmit").data("loading"));
    $.ajax({
        type : 'post',
        url : ctx + 'certLogin',
        data : data,
        dataType:'json',//接受数据格式
        async : false,
        success : function(r) {
            if (r.code == web_status.SUCCESS) {
                location.href = ctx + 'index';
            } else {
                $('.imgcode').click();
                $(".code").val("");
                $.modal.msg(r.msg);
            }
            $.modal.closeLoading();
        }
    });
}

function getRandom() {
    var random = '';
    $.ajax({
        type : 'get',
        url : ctx + 'random',
        data : {},
        dataType: 'json',//接受数据格式
        async : false,
        success : function(r) {
            if (r.code == web_status.SUCCESS) {
                random = r.data
            } else {
                $.modal.msg(r.msg);
            }
            $.modal.closeLoading();
        }
    });
    return random;
}

function validateUKeyRule() {
    var icon = "<i class='fa fa-times-circle'></i> ";
    $("#UKeySignupForm").validate({
        rules: {
            username: {
                required: true
            }
        },
        messages: {
            username: {
                required: icon + "请输入您的用户名",
            }
        }
    })
}

function validateKickout() {
    if (getParam("kickout") == 1) {
        layer.alert("<font color='red'>您已在别处登录，请您重新登录</font>", {
            icon: 0,
            title: "系统提示"
        },
        function(index) {
            //关闭弹窗
            layer.close(index);
            if (top != self) {
                top.location = self.location;
            } else {
                var url = location.search;
                if (url) {
                    var oldUrl = window.location.href;
                    var newUrl = oldUrl.substring(0, oldUrl.indexOf('?'));
                    self.location = newUrl;
                }
            }
        });
    }
}

function getParam(paramName) {
    var reg = new RegExp("(^|&)" + paramName + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return decodeURI(r[2]);
    return null;
}